package orm.base.Ex;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import orm.base.BaseModel;
import orm.base.BasePageInfo;
import orm.service.RedisService;
import wangchao.tools.CreateKey;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 张宏 on 2016/5/3.
 */
public class BaseEx {
    /**
     * 日志打印
     */
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    protected int sCode = 1;   //成功码
    protected int eCode = 0;   //失败码
    protected int login_eCode = -1; //登录失效
    protected String codeKey = "code";
    protected String messKey = "mess";
    protected String dataKey = "data";
    protected String sMess = "SUCCESS";

//    @Autowired
    protected RedisService redisService;

    /**
     * 时间格式化
     */
    protected SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    protected SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");

    protected SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMddHHmm");

    protected SimpleDateFormat yymmdd = new SimpleDateFormat("yyyyMMdd");

    /**
     * 获得当前时间字符串（yyyy-MM-dd HH:mm:ss）
     *
     * @return
     */
    public String now() {
        return sdf.format(new Date());
    }

    public JSONObject renderJSON(String value) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("value", value);
        jsonObject.put("color", "#173177");
        return jsonObject;
    }

    /**
     * 获得指定日期的前一天
     *
     * @return
     * @throws Exception
     */
    public String getSpecifiedDayBefore() {
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yy-MM-dd").parse(now());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day - 1);

        String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return dayBefore;
    }

    /**
     * 每个位置相加
     *
     * @param n
     * @return
     */
    public int sumDIgits(long n) {
        int tmp;
        int result = 0;
        Long m = new Long(n);
        tmp = m.intValue();
        while (tmp > 0) {
            result = tmp % 10 + result;
            tmp = tmp / 10;
        }
        return result;
    }

    /**
     * 自定义格式的时间字符串
     *
     * @param format
     * @return
     */
    public String now(String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date());
    }

    /**
     * 获得订单id
     *
     * @return
     */
    public String getOrderId() {
        return now("yyyyMMdd") + "-" + now("HHmmss") + "-" + CreateKey.getRandomString(4);
    }

    /**
     * 可以剔除某些字段的方法
     *
     * @param pl
     * @return
     */
    /**
     * 可以剔除某些字段的方法
     *
     * @param pl
     * @return
     */
    public JSONObject codeData(final Object pl) {
        JSONObject jsonObject = new JSONObject();
        if (pl instanceof BasePageInfo) {
            if (((BasePageInfo) pl).getSelectMenu() != null) {
                SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
                String[] params = ((BasePageInfo) pl).getSelectMenu().split(",");
                for (String param : params) {
                    filter.getIncludes().add(param);
                }
                jsonObject = JSONObject.parseObject(JSON.toJSONString(pl, filter));// ;
            } else {
                if (((BasePageInfo) pl).getRemoves().size() != 0) {
                    SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
                    filter.getExcludes().addAll(((BasePageInfo) pl).getRemoves());
                    jsonObject = JSONObject.parseObject(JSON.toJSONString(pl, filter));// ;
                } else {
                    jsonObject = (JSONObject) JSON.toJSON(pl);// ;
                }
            }
        } else if (pl instanceof BaseModel) {
            jsonObject = parseObject((BaseModel) pl);
        } else if (pl instanceof List) {
            List<Object> objects = new ArrayList<Object>();
            for (Object obj : (List<Object>) pl) {
                if (obj instanceof BaseModel) {
                    jsonObject = parseObject((BaseModel) obj);
                    //BaseModel baseModel = (BaseModel) JSON.toJavaObject(jsonObject, obj.getClass());
                    objects.add(jsonObject);
                } else {
                    objects.add(obj);
                }
            }
            JSONArray array = (JSONArray) JSON.toJSON(objects);
            JSONObject _jsonObject = new JSONObject();
            _jsonObject.put("list", array);
            return this.codeData(sCode, _jsonObject);
        } else if (pl instanceof Map) {
            jsonObject = (JSONObject) JSON.toJSON(pl);
        }
        return codeData(sCode, jsonObject);
    }

    /**
     * 封裝json導出
     *
     * @param obj
     * @return
     */
    private JSONObject parseObject(BaseModel obj) {
        JSONObject jsonObject;
        if (obj.getRemoves().size() != 0) {
            SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
            filter.getExcludes().addAll(obj.getRemoves());
            jsonObject = JSONObject.parseObject(JSON.toJSONString(obj, filter));// ;
        } else {
            jsonObject = (JSONObject) JSON.toJSON(obj);// ;
        }
        return jsonObject;
    }

    public JSONObject codeMess(int code, String str) {
        JSONObject jo = new JSONObject();
        jo.put(codeKey, code);
        jo.put(messKey, str);
        return jo;
    }

    public JSONObject codeData(int code, Object o) {
        JSONObject jo = new JSONObject();
        JSONObject ojo = null;
        if (o instanceof BaseModel)
            ojo = parseObject((BaseModel) o);
        jo.put(codeKey, code);
        jo.put(dataKey, ojo == null ? o : ojo);
        return jo;
    }

    /**
     * 字符串转int
     *
     * @param str
     */
    public static int toInt(String str) {
        if (str == null || str.equals(""))
            return 0;
        else
            return Integer.parseInt(str);
    }

    /**
     * 字符串转double(积分)
     *
     * @param str
     */
    public static double toDouble(String str) {
        if (str == null || str.equals(""))
            return 0d;
        else
            return Double.parseDouble(str);
    }

    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }


    /**
     * 解析投注信息
     *
     * @param kaij
     * @return
     * @throws Exception
     */
    public static String kjResult(String kaij) throws Exception {
        kaij = kaij.trim();
        if ("z".equals(kaij)) {
            return "庄";
        } else if ("x".equals(kaij)) {
            return "闲";
        } else if ("zd".equals(kaij)) {
            return "庄对";
        } else if ("xd".equals(kaij)) {
            return "闲对";
        } else {
            return "和";
        }
    }

    /**
     * 装载list<object>
     * @param list
     * @return
     * @throws Exception
     */
    protected List<Object> formList(List<Map> list) throws Exception{
        List<Object> objList = new ArrayList<>();

        for (Map<String, String> _map :list){
            List<Object> obj = new ArrayList<>();
            for (Map.Entry<String, String> entry : _map.entrySet()) {
                obj.add(entry.getValue());
            }
            objList.add(obj.toArray());
        }

        return objList;
    }

    public static int unAbs(int a) {
        return (a > 0) ? -a : a;
    }

}
